<template>
  <div class="box">
    <div class="title"> 人员选择</div>
    <el-collapse v-model="activeNames" @change="handleChange">
   
      <el-collapse-item title="本厂区" name="2">
        <div>
          <el-input size="small" placeholder="输入关键字进行过滤" v-model="filterTextUser"> </el-input>
          <div class="content">
            <span v-for="item in checkedList" :key="item.id">
                 <span class="name_span" v-if="item.type * 1 === 0">{{ item.label }}</span> 
              </span>
          </div>
            <div style="margin-top: 5px"></div>
            <el-tree
              :data="dataUser"
              :check-strictly="true" 
              :props="defaultPropsUser"
              :default-expand-all="false"
              :accordion="false"
              ref="treeUser"
              node-key="id"
              show-checkbox
              :default-expanded-keys="expandedKeys"
              :default-checked-keys="checkedKeys"
              highlight-current
              :filter-node-method="filterNode"
              @check-change="checkChange"
              @check="checksUser"
            >
            </el-tree>
        </div>
      </el-collapse-item>
      <el-collapse-item title="承包商" name="1" v-if="isContractorLocal">
        <div>
          <el-input size="small" placeholder="输入关键字进行过滤" v-model="filterContractor"> </el-input>
            <div style="margin-top:10px"></div>
            <div class="content">
              <span v-for="item in checkedList" :key="item.id">
                 <span class="name_span" v-if="item.type * 1 === 1">{{ item.label }}</span> 
              </span>
            </div>
            <div style="margin-top: 5px"></div>
          <el-tree
              :data="dataContractor"
              :check-strictly="true" 
              :props="defaultPropsUser"
              :default-expand-all="false"
              :accordion="false"
              ref="treeContractor"
              node-key="personId"
              show-checkbox
              :default-expanded-keys="expandedKeys"
              :default-checked-keys="checkedKeys"
              highlight-current
              :filter-node-method="filterNode"
              @check-change="checkChange"
              @check="checksContractor"
            >
            </el-tree>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div style="height: 45px;"></div>
    <div class="dialog_footer" style="margin-top: 5px;">
        <!-- <el-button @click="visiblePeople = false">取 消</el-button> -->
        <el-button type="success" @click="confirmUser">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { useSystemApi } from "@/api/systemApi";

export default {
  props: {
    // 默认多选
    multiple: {
      type: Boolean,
      default: true,
    },
    // c传入label 数组处理
    echoCheckedLabel: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 传入value
    echoCheckedValue: {
      type: Array,
      default: () => {
        return []
      }
    },
    isContractorLocal:{
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      isContractorStatus: this.isContractorLocal,
      checkedList: [],
      checkedListUser: [],
      checkedListContractor: [],
      activeNames: ['1', '2'],
      // 本厂区
      expandedKeys: [], // 数据回显
      checkedKeys: [], // 数据回显
      dataUser: [],
      defaultPropsUser: {
        children: "children",
        label: "label",
      },
      filterTextUser: '',

      // 第三方
      dataContractor: [],
      filterContractor: ''
    };
  },
  methods: {
    confirmUser() {
      // console.log(this.checkedList, 'setCheckedList')
      this.$emit('setCheckedList', this.checkedList)
    },
    // 获取接口数据  本厂区
    getUserSelect() {
      useSystemApi().apiUserTree({COMPANYID: ''}).then((res) => {
        // this.dataUser = res.info
        this.dataUser = this.processArray(res.info)
 
        // console.log(this.echoCheckedValue, '回显数据--本厂区')
        // console.log(this.echoCheckedLabel, '回显数据-本厂区')
        if (this.echoCheckedLabel.length !== 0) {
          const result = this.findFields(this.dataUser, this.echoCheckedLabel);
          // console.log(result, 'result')
          this.expandedKeys = result.map((i) => {return i.id})
          this.checkedKeys = result.map((i) => {return i.id})
          // this.$emit('setCheckedList', result)
          this.checkedListUser = result
          this.checkedList = this.checkedList.concat(result)
          // console.log(this.checkedList, 'checkedList')
        } else {
          // this.echoCheckedLabel = []
          // this.$emit('setCheckedList', [])
        }
        if (this.echoCheckedValue.length !== 0) {
          // console.log(222)
          this.expandedKeys = this.echoCheckedValue
          this.checkedKeys = this.echoCheckedValue
        } else {
          // this.$emit('setCheckedList', [])
          // this.expandedKeys = []
          // this.checkedKeys = []
        }
      });
    },
    processArray(data) {
        let newArray = [];
        data.forEach(item => {
            let newItem = { ...item }; 
            if (item.children.length === 0 && item.disabled === 0) {
                newItem.type = 0
                newItem.personId = item.id
                newItem.name = item.label
                newItem.phoneNum = '1231345646'
            }
            if (item.children.length > 0) {
                newItem.children = this.processArray(item.children);
            }
            newArray.push(newItem);
        });
        return newArray;
    },
     // 多选
    checksContractor(val, node) {
      if (!this.multiple) return false
      this.checkedListContractor = node.checkedNodes
      // console.log(node.checkedNodes)
      this.checkedList = this.checkedListContractor.concat(this.checkedListUser)
      // console.log(this.checkedList)
    },
    // 本厂区多选
    checksUser(val, node) {
      if (!this.multiple) return false
      this.checkedListUser = node.checkedNodes
      // console.log(node.checkedNodes)
      this.checkedList = this.checkedListUser.concat(this.checkedListContractor)
      // console.log(this.checkedListContractor)
      // console.log(this.checkedList)

    },
    // 单选
    checkChange(item, node) {
      if (this.multiple) return false
      if (node === true) {
        // 点击未选中复选框
        this.$refs.treeUser.setCheckedKeys([]);
        // this.$refs.treeContractor.setCheckedKeys([])
        this.$refs.treeUser.setCheckedKeys([item.id]); // 单选
        // this.$refs.treeContractor.setCheckedKeys([item.personId]); // 单选
        // console.log(item)
        this.checkedList = [item] //
        // console.log(this.checkedList)
        // this.$emit('setCheckedList', this.checkedList)
      }
    },
    filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
    },
    findFields(data, fields) {
      let result = [];
      function search(children) {
        for (let i = 0; i < children.length; i++) {
          const child = children[i];

          if (fields.includes(child.label)) {
            result.push(child);
          }

          if (child.children) {
            search(child.children);
          }
        }
      }
      search(data);
      return result;
    },
    handleChange() {
    },
    // 第三方
    getContractorUnit() {
      this.$network.contractor.findAllContractorPage({
            current:1,
            size: 100000,
            msginfo: "",
          }).then((response) => {
            let list = response.data.data.records.map((i) => { return { ...i, label:i.contractorName, disabled: true, children: []}})
            this.getContractorUser(list)
          }).catch((error) => {
            this.$message.error(error.message);
          });
      // 
    },
    // 部门人员生成
    getContractorUser(unitList) {
      this.$network.contractor.findConUserUrl({
          }).then((response) => {
            // 添加label 统一化  type区分类型
            let userList = response.data.data.map((i) => { return { ...i, label:i.name, type: 1, children: []}})
            let updatedUnitList = unitList.map(unit => {
              let users = userList.filter(user => user.contractorId === unit.contractorId);
              return { ...unit, children: users };
            });
            // console.log(updatedUnitList);
            this.dataContractor = updatedUnitList
            // console.log(this.dataContractor)
            
            const result = this.findFields(this.dataContractor, this.echoCheckedLabel)
            this.checkedListContractor = result
            this.checkedList = this.checkedList.concat(result)
            // console.log(this.checkedList, 'checkedList部门人员生成')

            this.expandedKeys = this.checkedList.map((i) => {return i.personId})
            this.checkedKeys = this.checkedList.map((i) => {return i.personId})
          }).catch((error) => {
            this.$message.error(error.message);
          });
    },
    
  },
  mounted() {
    this.getUserSelect()
    console.log(this.isContractorLocal, 'isContractorLocal')
    // this.getContractorUnit()
  },
  watch: {
    filterTextUser(val) {
      this.$refs.treeUser.filter(val);
    },
    filterContractor(val) {
      this.$refs.treeContractor.filter(val);
    }
  },
};
</script>

<style lang="scss" scoped>
.box {
  padding: 10px;
  width: 100%;

  .title {
    font-weight: 900;
    padding-bottom: 10px;
  }
  .content {
    padding: 5px;
    margin-top: 5px;
    height: 70px;
    border: 1px solid #f5f0f0;
    background-color: whitesmoke;
  }

  .name_span {
    padding: 5px;
    border: 1px solid #bdb2b2;
    background-color: white;
    margin: 5px;
}
.dialog_footer {
  position: fixed;
  padding: 0 0 5px 0;
  bottom: 0px;
  text-align: center;
  z-index: 9999;
  margin: 0 auto;
}
}
</style>